const app = getApp()

Page({
  data: {
    addresses: [],
    showForm: false,
    formData: {
      id: '',
      name: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      address: '',
      is_default: false
    },
    region: ['请选择', '请选择', '请选择']
  },

  onLoad() {
    // 移除onLoad中的loadAddresses调用
  },

  onShow() {
    this.loadAddresses()
  },

  loadAddresses() {
    const token = wx.getStorageSync('access_token')
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login?redirect=' + encodeURIComponent('/pages/address/address')
      })
      return
    }

    wx.showLoading({
      title: '加载中...'
    })

    wx.request({
      url: `${app.globalData.baseUrl}/users/addresses/`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            addresses: res.data.results || res.data
          })
        } else if (res.statusCode === 401) {
          const refreshToken = wx.getStorageSync('refresh_token')
          if (refreshToken) {
            this.refreshToken(refreshToken)
          } else {
            this.clearTokenAndRedirect()
          }
        }
      },
      fail: () => {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  refreshToken(refreshToken) {
    wx.request({
      url: `${app.globalData.baseUrl}/token/refresh/`,
      method: 'POST',
      data: {
        refresh: refreshToken
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.setStorageSync('access_token', res.data.access)
          this.loadAddresses()
        } else {
          this.clearTokenAndRedirect()
        }
      },
      fail: () => {
        this.clearTokenAndRedirect()
      }
    })
  },

  clearTokenAndRedirect() {
    wx.removeStorageSync('access_token')
    wx.removeStorageSync('refresh_token')
    wx.redirectTo({
      url: '/pages/login/login?redirect=' + encodeURIComponent('/pages/address/address')
    })
  },

  addAddress() {
    this.setData({
      showForm: true,
      formData: {
        id: null,
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        address: '',
        is_default: false
      },
      region: ['请选择', '请选择', '请选择']
    })
  },

  editAddress(e) {
    const id = e.currentTarget.dataset.id
    const address = this.data.addresses.find(addr => addr.id === id)
    this.setData({
      showForm: true,
      formData: { ...address },
      region: [address.province, address.city, address.district]
    })
  },

  closeForm() {
    this.setData({ showForm: false })
  },

  bindRegionChange(e) {
    const region = e.detail.value
    this.setData({
      region,
      'formData.province': region[0],
      'formData.city': region[1],
      'formData.district': region[2]
    })
  },

  updateFormData(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value
    })
  },

  switchDefault(e) {
    this.setData({
      'formData.is_default': e.detail.value
    })
  },

  saveAddress() {
    const { formData } = this.data
    
    // 表单验证
    if (!formData.name) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      })
      return
    }
    if (!formData.phone) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      })
      return
    }
    if (!formData.province || !formData.city || !formData.district) {
      wx.showToast({
        title: '请选择所在地区',
        icon: 'none'
      })
      return
    }
    if (!formData.address) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '保存中...'
    })

    const token = wx.getStorageSync('access_token')
    const method = formData.id ? 'PUT' : 'POST'
    const url = formData.id 
      ? `${app.globalData.baseUrl}/users/addresses/${formData.id}/`
      : `${app.globalData.baseUrl}/users/addresses/`

    // 准备要发送的数据
    const requestData = {
      name: formData.name,
      phone: formData.phone,
      province: formData.province,
      city: formData.city,
      district: formData.district,
      address: formData.address,
      is_default: formData.is_default
    }

    wx.request({
      url,
      method,
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: requestData,
      success: (res) => {
        if (res.statusCode === 200 || res.statusCode === 201) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
          // 先关闭表单
          this.setData({ 
            showForm: false,
            formData: {
              id: '',
              name: '',
              phone: '',
              province: '',
              city: '',
              district: '',
              address: '',
              is_default: false
            },
            region: ['请选择', '请选择', '请选择']
          }, () => {
            // 在回调中重新加载地址列表
            setTimeout(() => {
              this.loadAddresses()
            }, 300)
          })
        } else if (res.statusCode === 401) {
          const refreshToken = wx.getStorageSync('refresh_token')
          if (refreshToken) {
            this.refreshToken(refreshToken)
          } else {
            this.clearTokenAndRedirect()
          }
        } else {
          console.error('保存失败:', res);
          wx.showToast({ title: res.data.detail || '保存失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err)
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  setDefault(e) {
    const id = e.currentTarget.dataset.id
    const token = wx.getStorageSync('access_token')
    
    wx.request({
      url: `${app.globalData.baseUrl}/users/addresses/${id}/set_default/`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '设置成功',
            icon: 'success'
          })
          // 重新加载地址列表
          this.loadAddresses()
        } else {
          wx.showToast({
            title: '设置失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '设置失败',
          icon: 'none'
        })
      }
    })
  },

  deleteAddress(e) {
    const id = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这个地址吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...'
          })

          const token = wx.getStorageSync('access_token')
          wx.request({
            url: `${app.globalData.baseUrl}/users/addresses/${id}/`,
            method: 'DELETE',
            header: {
              'Authorization': `Bearer ${token}`
            },
            success: (res) => {
              if (res.statusCode === 204) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                setTimeout(() => {
                  this.loadAddresses()
                }, 300)
              } else if (res.statusCode === 401) {
                const refreshToken = wx.getStorageSync('refresh_token')
                if (refreshToken) {
                  this.refreshToken(refreshToken)
                } else {
                  this.clearTokenAndRedirect()
                }
              }
            },
            complete: () => {
              wx.hideLoading()
            }
          })
        }
      }
    })
  }
})